<template>
  <div class="yygh_bg">
   
    <search-bar :menu="menu" :activeitem="activeitem"></search-bar>
    <position>
      <router-link to="/cloud">云诊室</router-link>
      &gt;
      <span class="last">云预约</span>
    </position>
    <steps :step="0" :text="['选择科室医生', '填写问诊信息', '支付费用', '预约成功', '等待医生视频', '完成就诊']"></steps>

    <div class="yybox four-cornor-wrapper">
      <i class="l"></i>
      <i class="r"></i>
      <i class="t"></i>
      <i class="b"></i>
      <div class="yycontent">
        <div class="yycontent_title">科室查找</div>
        <div class="select_tab">
          <div class="yyzs">
            <div class="appbb_body">
              <div id="keshilist" class="appbb_content">

                <div class="appbb_keshi_box" v-for="item in departments" :key="item.id">
                  <div>
                    <div class="appbb_keshi_title">
                      {{item.categoryText}}
                    </div>
                    <div class="appbb_keshi_list">
                      <div v-for="dept in item.deptInfos" :class="['appbb_keshi_item', localDeptId === dept.localDeptId ? 'active': '']" :key="dept.deptId" >
                        <router-link :to="'/cloud?deptId='+dept.deptId+'&localDeptId='+dept.localDeptId">{{dept.deptName}}</router-link>
                      </div>
                    </div>
                  </div>
                  <div class="group_line2"></div>
                </div>

              </div>
            </div>
          </div>
        </div>
        <div class="doctor-wrapper" v-if="doctors.length > 0" style="min-height:200px;">

          <div class="doctor_tab" v-for="(doctor, index) in doctors" :key="doctor.localDoctorId">
            <div class="doctor_inform">
              <div class="avatar" @click="goDoctor(doctor)">
                <img class="doctor-image" :alt="doctor.doctorName" v-lazy="DOCTOR_AVATAR+doctor.localDoctorId+'.jpg'"/>
              </div>
              <div class="desc">
                <p class="name">{{doctor.doctorName || doctor.regDeptName}}</p>
                <p class="title">{{doctor.doctorLevelText || '&nbsp;'}}</p>
                <p class="area">{{doctor.speciality || '&nbsp;'}}</p>
                <p class="click_detail" v-show="doctor.doctorName">
                  <a href="javascript:;"  @click="goDoctor(doctor)">点击查看详情&gt;</a>
                </p>
              </div>
            </div>
            <div class="doctor_schedule">
              <ul>
                <li class="backward">
                  <div title="上一周" :class="['form_title', doctor.prevPage ? 'active_arrow': '']" @click="prevPage(index, doctor)"></div>
                  <div class="morning">上午</div>
                  <div class="noon">下午</div>
                </li>
                <div class="list-wrapper">
                  <div class="list-scroller" :id="'listScroller'+index">
                    <li class="single_day" v-for="(day, i) in days" :key="day.orderDate1">
                      <div class="form_title">
                        {{day.orderDate1}}
                        <br/>
                        {{day.orderWeek2}}
                      </div>
                      <div class="morning" v-html="doctor.doctorDays[i].morning" @click="appointClickMorning(doctor.doctorDays[i], doctor, day)"></div>
                      <div class="noon" v-html="doctor.doctorDays[i].noon" @click="appointClickNoon(doctor.doctorDays[i], doctor, day)"></div>
                    </li>
                  </div>
                </div>
                <li class="forward">
                  <div title="下一周" :class="['form_title', doctor.nextPage ? 'active_arrow': '']" @click="nextPage(index, doctor)"></div>
                  <div class="morning"></div>
                  <div class="noon"></div>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="no-data" v-else>
          {{noDataMessage}}
        </div>
      </div>

    </div>
    <!-- 用户须知 第一次访问弹出 -->
    <div class="mask" v-if="mask_shown">
      <div class="alert_box four-cornor-wrapper">
        <i class="l"></i>
        <i class="r"></i>
        <i class="t"></i>
        <i class="b"></i>
        <div class="box_title">
          <span>用户须知</span>
        </div>
        <b class="clost_btn" v-on:click="mask_shown = false"></b>
        <div class="msg_content">
          <p v-for="msg in msg_content" v-bind:class="msg.class" :key="msg.class">{{msg.content}}</p>
        </div>
        <div class="center">
          <a href="javascript:;" class="common-main-button" @click="argeeHandle">我已知晓</a>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogShow" custom-class="dialog-common">
      <div class="dialog-title" slot="title">
        请选择就诊时段 <small class="t1">{{dialogTitle}}</small>
      </div>
      <div class="select-time">
        <div class="time-box" v-for="time in times" :key="time.startTime">
          <a href="javascript:;" v-if="time.availableCount > 0" @click="timeClick(time)" :class="['sprites',time.isActive ? 'active' : '']">{{time.startTime}} - {{time.endTime}}</a>
          <a href="javascript:;" :class="['sprites','disable']" v-else>{{time.startTime}} - {{time.endTime}}</a>
        </div>
      </div>
      <div class="center" slot="footer">
        <a href="javascript:;" class="common-main-button"  @click="confirmHandle">确定</a>
        <a href="javascript:;"  class="common-sub-button" @click="dialogShow=false">取消</a>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="doctor_tips_show" custom-class="dialog-common">
      <div class="dialog-title" slot="title">
        温馨提示
      </div>
      <div class="t6">{{FAMUSE_DOCTOR_TIPS}}</div>
      <h1 class="center">
        <img src="../../assets/qrcode.png" style="width:160px;" />
      </h1>
      <div class="center" slot="footer">
        <a href="javascript:;" class="common-main-button"  @click="doctor_tips_show=false">确定</a>
      </div>
    </el-dialog>

    <div class="ad">
      <a :href="CLOUD_EXE" class="download">为了确保与医生能够正常沟通，请下载视频通道</a>
      <img src="../../assets/ad.png" />
    </div>

    <el-dialog :visible.sync="cloud_tips_show" size="tiny" title="温馨提示">
      <div class="t6">
        <span>为确保正常使用云诊室，请提前下载安装视频通道</span>
      </div>
      <div class="center" slot="footer">
        <a :href="CLOUD_EXE" class="common-sub-button">下载视频通道</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="javascript:;" class="common-main-button"  @click="cloud_tips_show=false">我已知晓</a>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    commonAjax,
    ORG_ID,
    PLATFORM_PREFIX,
    DOCTOR_LEVEL,
    APPOINT_TIPS,
    DOCTOR_AVATAR,
    FAMUSE_DOCTORS,
    FAMUSE_DOCTOR_TIPS,
    CLOUD_MENU,
    CLOUD_EXE
  } from '../../api/api'
  import Steps from '../../components/Steps'
  import Position from '../../components/Position'
  import SearchBar from '../../components/SearchBar'
  import $ from 'jquery'

  export default {
    components: {Steps, Position, SearchBar},
    data () {
      return {
        menu: CLOUD_MENU,
        activeitem: 0,
        departments: [],
        days: [],
        doctors: [],
        times: [],
        DOCTOR_LEVEL: DOCTOR_LEVEL,
        mask_shown: false,
        dialogShow: false,
        dialogTitle: '',
        msg_content: [],
        noDataMessage: '暂无数据',
        DOCTOR_AVATAR: DOCTOR_AVATAR,
        FAMUSE_DOCTORS: FAMUSE_DOCTORS,
        FAMUSE_DOCTOR_TIPS: FAMUSE_DOCTOR_TIPS,
        isMorning: true,
        localDeptId: '',
        deptId: '',
        doctor_tips_show: false,
        cloud_tips_show: false,
        base64EncodeChars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
        CLOUD_EXE: CLOUD_EXE
      }
    },
    watch: {
      $route () {
        this.deptId = this.$route.query.deptId
        this.localDeptId = this.$route.query.localDeptId
        this.getDoctors(this.$route.query)
      }
    },
    mounted () {
      // 检查客户端是否安装
      this.CheckInstall()
      // 权限验证
      if (!localStorage.accessToken) {
        this.$message({message: '请先登录', type: 'error'})
        return
      }
      if (!localStorage.person) {
        setTimeout(() => this.$router.push('/personal?from=login'), 400)
      }

      if (this.$route.query.localDeptId && this.$route.query.deptId) {
        this.deptId = this.$route.query.deptId
        this.localDeptId = this.$route.query.localDeptId
      }
      // 获取科室列表
      this.$store.commit('UPDATE_LOADING')
      commonAjax([ORG_ID, '2'], `${PLATFORM_PREFIX}.deptService`, 'findCategoryAndDept').then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 200) {
          this.departments = res.data.body || []
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      }).catch(res => {
        this.$store.commit('UPDATE_LOADING')
        localStorage.removeItem('accessToken')
        location.reload()
      })
      // 获取排版周期
      commonAjax(
        [ORG_ID, '', '', '2'],
        `${PLATFORM_PREFIX}.registrationService`,
        'getTimePeriod'
      ).then(res => {
        if (res.data.code === 200) {
          this.days = res.data.body
          if (this.$route.query.localDeptId && this.$route.query.deptId) {
            this.getDoctors(this.$route.query)
          }
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      }).catch(res => console.warn(res))
    },
    methods: {
      appointClickMorning (doctorDays, doctor, day) {
        this.isMorning = true
        if (!doctorDays.morningActive) {
          return false
        }
        this.saveInfo(doctorDays, doctor, day)
      },
      appointClickNoon (doctorDays, doctor, day) {
        this.isMorning = false
        if (!doctorDays.noonActive) {
          return false
        }
        this.saveInfo(doctorDays, doctor, day)
      },
      goDoctor (doctor) {
        if (!doctor.doctorName) {
          return false
        }
        // localStorage.doctor = JSON.stringify(doctor)
        this.$router.push({
          path: '/yygh/doctor',
          query: {
            localDeptId: doctor.localDeptId,
            localDoctorId: doctor.localDoctorId
          }
        })
      },
      saveInfo (doctorDays, doctor, day) {
        //  this.$alert(FAMUSE_DOCTOR_TIPS, '温馨提示')
        // 过滤部分名医，提示只能在APP预约
        if (doctor && doctor.doctorName) {
          if (FAMUSE_DOCTORS.indexOf(doctor.doctorName) > -1) {
            this.doctor_tips_show = true
            return
          }
        }

        if (this.isMorning) {
          localStorage.dep = JSON.stringify(doctorDays.morningDepInfo)
        } else {
          localStorage.dep = JSON.stringify(doctorDays.noonDepInfo)
        }
        localStorage.day = JSON.stringify(day)
        localStorage.doctor = JSON.stringify(doctor)
        if (localStorage.firstcome === '1') {
          this.argeeHandle()
        } else {
          localStorage.firstcome = '1'
          this.showDialog()
        }
      },
      timeClick (time) {
        this.times.forEach(v => { v.isActive = false })
        time.isActive = true
        localStorage.time = JSON.stringify(time)
      },
      showDialog () {
        this.mask_shown = true
        this.msg_content = APPOINT_TIPS
      },
      argeeHandle () {
        let dep = JSON.parse(localStorage.dep)
        let day = JSON.parse(localStorage.day)
        let doctor = JSON.parse(localStorage.doctor)
        // 获取号源时间段
        this.mask_shown = false
        this.$store.commit('UPDATE_LOADING')
        commonAjax(
          [ORG_ID, dep.localRegDeptId, doctor.localDoctorId || '', dep.workDate, dep.seqId, '2'],
          `${PLATFORM_PREFIX}.registrationService`,
          'getDocAndDeptSouce'
        ).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 200 && res.data.body.length > 0) {
            this.dialogTitle = `（科室：${doctor.regDeptName} —— 时间：${day.orderDate}）`
            this.dialogShow = true
            let d = res.data.body
            d.forEach(v => { v.isActive = false })
            this.times = d
          } else {
            this.$message({
              message: '抱歉，该医生的号源已经预约完',
              type: 'error'
            })
          }
        }).catch(res => {
          this.$message({
            message: res,
            type: 'error'
          })
        })
      },
      confirmHandle () {
        let isSelect = this.times.some(time => time.isActive === true)
        if (isSelect) {
          this.$router.push('/cloud/confirm')
        } else {
          return false
        }
      },
      getDoctors (dept) {
        let _this = this
        this.doctors = []
        // 获取医生列表
        localStorage.dept = JSON.stringify(dept)
        this.$store.commit('UPDATE_LOADING')
        commonAjax(
          [ORG_ID, '', dept.localDeptId, dept.deptId, '2'], `${PLATFORM_PREFIX}.registrationService`,
          'getDoctorDeptListPc'
        ).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 200 && res.data.body.length > 0) {
            res.data.body.forEach(v => {
              let temp = []
              v.prevPage = false
              v.nextPage = true
              this.days.forEach(a => {
                temp.push({
                  morning: '',
                  noon: '',
                  morningActive: false,
                  noonActive: false,
                  morningDepInfo: '',
                  noonDepInfo: ''
                })
              })
              v.doctorDays = temp
            })
            this.doctors = res.data.body || []
            this.days.forEach((day, index) => {
              this.doctors.forEach(doc => {
                let depDocPlanPcs = doc.depDocPlanPcs
                if (Array.isArray(depDocPlanPcs)) {
                  depDocPlanPcs.forEach(dep => {
                    _this.getSameDay(day, index, doc, dep)
                  })
                }
              })
            })
          } else {
            this.$message({
              message: res.data.msg || '暂无数据',
              type: 'error'
            })
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
        })
      },
      getSameDay (day, index, doc, dep) {
        if (doc.speciality === 'NULL') {
          doc.speciality = ''
        }
        if (dep.workDate === day.orderDate) {
          if (dep.planTime === '1') {
            doc.doctorDays[index].morningDepInfo = dep
            if (dep.stopFlag === '1') {
              doc.doctorDays[index].morning = '<div class="book_state_5">已停诊</div>'
            } else if (dep.status === '2') {
              doc.doctorDays[index].morning = '<div class="book_state_4">已约满</div>'
            } else if (dep.status === '3') {
              doc.doctorDays[index].morning = '<div class="book_state_4">现场号</div>'
            } else {
              doc.doctorDays[index].morning = '<div class="book_state_1">可预约</div>'
              doc.doctorDays[index].morningActive = true
            }
          } else {
            doc.doctorDays[index].noonDepInfo = dep
            if (dep.stopFlag === '1') {
              doc.doctorDays[index].noon = '<div class="book_state_5">已停诊</div>'
            } else if (dep.status === '2') {
              doc.doctorDays[index].noon = '<div class="book_state_4">已约满</div>'
            } else if (dep.status === '3') {
              doc.doctorDays[index].morning = '<div class="book_state_4">现场号</div>'
            } else {
              doc.doctorDays[index].noon = '<div class="book_state_1">可预约</div>'
              doc.doctorDays[index].noonActive = true
            }
          }
        }
      },
      nextPage (index, doctor) {
        if (!doctor.nextPage) {
          return false
        }
        let elem = 'listScroller' + index
        document.getElementById(elem).style.transform = 'translate3d(-50%, 0, 0)'
        doctor.nextPage = !doctor.nextPage
        doctor.prevPage = !doctor.prevPage
      },
      prevPage (index, doctor) {
        if (!doctor.prevPage) {
          return false
        }
        let elem = 'listScroller' + index
        document.getElementById(elem).style.transform = 'translate3d(0, 0, 0)'
        doctor.nextPage = !doctor.nextPage
        doctor.prevPage = !doctor.prevPage
      },
      base64encode (str) {
        var out, i, len
        var c1, c2, c3
        var self = this

        len = str.length
        i = 0
        out = ''
        while (i < len) {
          c1 = str.charCodeAt(i++) & 0xff
          if (i === len) {
            out += self.base64EncodeChars.charAt(c1 >> 2)
            out += self.base64EncodeChars.charAt((c1 & 0x3) << 4)
            out += '==='
            break
          }
          c2 = str.charCodeAt(i++)
          if (i === len) {
            out += self.base64EncodeChars.charAt(c1 >> 2)
            out += self.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
            out += self.base64EncodeChars.charAt((c2 & 0xF) << 2)
            out += '='
            break
          }
          c3 = str.charCodeAt(i++)
          out += self.base64EncodeChars.charAt(c1 >> 2)
          out += self.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
          out += self.base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6))
          out += self.base64EncodeChars.charAt(c3 & 0x3F)
        }
        return out
      },
      CheckInstall (form) {
        var self = this
        var jsonText = this.getCheckInstall('117.78.40.139', 17979)
        var jsonTextBase64 = this.base64encode(self.utf16to8(jsonText))
        this.executeCheckInstall(jsonTextBase64)
      },
      utf16to8 (str) {
        var out, i, len, c
        out = ''
        len = str.length
        for (i = 0; i < len; i++) {
          c = str.charCodeAt(i)
          if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i)
          } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
          } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
          }
        }
        return out
      },
      getCheckInstall (serverAddress, serverPort) {
        var jsonText = '{' +
          '"Server": {' +
          '"Address": "' + serverAddress + '",' +
          '"Port": ' + serverPort +
          '},' +
          '"Action": {' +
          '"Name": "CheckInstall",' +
          '"Parameters": {' +
          '}' +
          '}' +
          '}'
        return jsonText
      },
      executeCheckInstall (jsonTextBase64) {
        var theResult = -1
        var self = this
        $.ajax(
          {
            type: 'GET',
            url: 'http://127.0.0.1:17979/INSTALL',
            data: 'URL=INSTALL://' + jsonTextBase64 + '/',
            dataType: 'jsonp',
            jsonp: 'jsonpCallback',
            success: function (data) {
              theResult = 0
              // message代表版本
              console.log(data.message)
            },
            error: function () {
              theResult = 0
              console.log('ajax error!')
            }
          }
        )
        setTimeout(function () {
          if (theResult !== 0) {
            self.cloud_tips_show = true
          }
        }, 500)
      }
    }
  }
</script>

<style lang="less">
  @import '../../common/css/vars.less';

  .doctor_tab li {
    float: left;
  }

  .appbb_keshi_box {
    position: relative;
    margin-top: 20px;
  }

  .appbb_keshi_title {
    display: inline-block;
    position: absolute;
    width: 120px;
    text-align: center;
    top: 0;
    left: 0;
    line-height: 26px;
  }

  .appbb_keshi_title:after {
    content: '';
    height: 20px;
    width: 2px;
    background: #cb9990;
    display: block;
    position: absolute;
    top: 5px;
    right: -2px;
  }

  .appbb_body .appbb_content .appbb_keshi_list {
    display: inline-block;
    width: 850px;
    margin-left: 150px;
  }

  .appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item {
    display: inline-block;
    margin-right: 1px;
    vertical-align: top;
    font-size: 14px;
    padding: 1px;
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 4px;
    line-height: 20px;
    margin-bottom: 5px;
  }

  .appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item.active {
    background: none 0% 0% repeat scroll rgb(238, 113, 0);
  }

  .appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item.active a {
    color: #fff;
  }

  .appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item a {
    display: inline-block;
    padding: 2px;
    color: #333;
    &:hover {
      color: @color-primary;
    }
  }

  .yybox {
    width: 1080px;
    margin: auto;
    background: #fff;
  }

  .side {
    width: 1080px;
    height: 27px;
    background: url('../../assets/box_side.jpg') 0 0 no-repeat;
    background-size: 100% 100%;
  }

  .side_up {
    transform: rotate(180deg);
  }

  .yycontent {
    width: 1080px;
  }

  .select_tab {
    border: 1px solid #f8e6e2;
    width: 1050px;
    margin: auto;
    margin-top: 20px;
    background: #FFFBF8;
    padding: 10px;
  }

  .yycontent_title {
    padding: 20px 40px 0;
    font-size: 24px;
    color: #EE7100;
  }

  .recent {
    padding: 10px 0 20px;
    border-bottom: 1px solid #f8e6e2;
  }

  .recent ul,
  .recent li {
    display: inline-block;
  }

  .recent li {
    margin: 0 20px;
    cursor: pointer;
  }

  .recent li.origin {
    color: #666;
    cursor: default;
  }
  .recent .clear {
    float: right;
    margin-right: 20px;
    color: #999;
    cursor: pointer;
  }

  .doctor_tab {

    width: 1050px;
    margin: 10px auto 0;
    overflow: hidden;
  }

  .doctor_tab:nth-child(3) {
    margin-top: 20px;
  }

  .doctor_inform {
    overflow: hidden;
    border: 1px solid #f8e6e2;
    border-right: 0;
    width: 310px;
    float: left;
    background: #FFFBF8;
  }



  .doctor_inform {
    .avatar {
      float: left;
      margin: 10px;
      position: relative;
      height: 128px;
      cursor: pointer;
    }
    .desc {
      margin: 10px 10px 10px 120px;
      position: relative;
      height: 128px;
    }
    .name {
      color: #a4381e;
      font-weight: bold;
      margin-bottom: 8px;
    }
    .title {
      line-height: 1.4;
      margin-bottom: 8px;
      font-size: 12px;
    }
    .area {
      color: #999;
      overflow: hidden;
      height: 3.4em;
      font-size: 12px;
      line-height: 1.4;
    }

  }


  .click_detail {
    position: absolute;
    bottom: 0;
    cursor: pointer;
    margin-bottom: 0;
    line-height: 1;
    width: 120px;
  }
  .doctor-image {
    width: 100px;
    height: 126px;
    border: none;
  }
  .ad {
    position: fixed;
    right: 0;
    bottom: 0;
    display:flex;
    flex-direction: column;
    width: 120px;
    z-index: 9999;
  }
  .download{
    font-size:18px;
    font-weight:bold;
    padding:10px;
    text-decoration: underline;
  }
</style>
